﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Web.Security;
using System.Linq;

namespace DynDns
{
    public partial class Control_Server : System.Web.UI.UserControl
    {
        ChangeConfigValue ccV;                  // Class to Read/Write IP
        String currentIP;
        int timeout = 500;                      // 500ms
        string rolle;

        protected void Page_Load(object sender, EventArgs e)
        {
            SiteMapDataSource1.Provider = SiteMap.Providers["Default"];
            ccV = new ChangeConfigValue();

            // 1. read server name
            String name = ccV.readIP("servername");
            // 2. read ip
            currentIP = ccV.readIP(name);

            // read Cookie
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
            rolle = ticket.CookiePath;
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow) 
            {
                // Check IF allowed for User, read Discription
                SiteMapNode myR = (SiteMapNode)e.Row.DataItem;

                // rolle Array from User
                string[] rollArray = rolle.Split(';');
                //rollArray = new string[] { rolle };
                
                if (myR.Description.ToString() == "" || rollArray.Contains(myR.Description.ToString()))
                {
                    e.Row.Visible = true;               // sichtbar für alle
                }
                else {
                    e.Row.Visible = false;               // nicht sichtbar
                }


            }
        }


        protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // Check IF allowed for User, read Discription
                SiteMapNode myR = (SiteMapNode)e.Row.DataItem;

                // rolle Array from User
                string[] rollArray = rolle.Split(';');
                //rollArray = new string[] { rolle };

                // Show On/Offline Panel
                Panel pOn = (Panel)e.Row.Cells[2].FindControl("PanelOnline");
                Panel pOff = (Panel)e.Row.Cells[2].FindControl("PanelOffLine");

                if (myR.Description.ToString() == "" || rollArray.Contains(myR.Description.ToString()) )
                {
                    e.Row.Visible = true;               // sichtbar für alle

                    HyperLink hlinke = (HyperLink)e.Row.Cells[1].FindControl("HyperLinkServerUrl");
                    Button hBtn = (Button)e.Row.Cells[1].FindControl("BtnServerUrl");
                                        
                    string nav = hlinke.NavigateUrl;
                    if (nav.Contains('|'))
                    {
                        // dont check the full url - it will some wake up the server
                        // use for wol only the main IP

                        string[] endUrl = nav.Split('|');

                        hlinke.Visible = false;
                        hBtn.Visible = true;
                        hBtn.PostBackUrl = "http://" + currentIP + endUrl[0] + endUrl[1];
                        hBtn.Text = e.Row.Cells[0].Text;

                        if (ConnectionAvailable("http://" + currentIP + endUrl[0]) == true)
                        {
                            pOn.Visible = true;
                            pOff.Visible = false;
                            e.Row.Cells[2].ToolTip = "Online";
                        }
                        else
                        {
                            pOn.Visible = false;
                            pOff.Visible = true;
                            e.Row.Cells[2].ToolTip = "Offline";
                        }
                        

                    }
                    else
                    {
                        hlinke.NavigateUrl = "http://" + currentIP + nav;
                        hlinke.Text = hlinke.NavigateUrl;

                        if (ConnectionAvailable(hlinke.NavigateUrl) == true)
                        {
                            pOn.Visible = true;
                            pOff.Visible = false;
                            e.Row.Cells[2].ToolTip = "Online";
                        }
                        else
                        {
                            pOn.Visible = false;
                            pOff.Visible = true;
                            e.Row.Cells[2].ToolTip = "Offline";
                        }
                    }
                }
                else
                {
                    e.Row.Visible = false;               // nicht sichtbar
                }

            }



        }

        // TEST Connection
        public bool ConnectionAvailable(string strServer)
        {
            ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
            {
                return true;
            };

            try
            {
                HttpWebRequest reqFP = (HttpWebRequest)HttpWebRequest.Create(strServer);
                reqFP.Timeout = timeout;

                HttpWebResponse rspFP = (HttpWebResponse)reqFP.GetResponse();
                if (HttpStatusCode.OK == rspFP.StatusCode)
                {
                    // HTTP = 200 - Internet connection available, server online
                    rspFP.Close();
                    return true;
                }
                else
                {
                    // Other status - Server or connection not available
                    rspFP.Close();
                    return false;
                }
            }
            catch (WebException we)
            {
                // Exception - connection not available
                if (we.Response != null | we.Status.ToString() == "TrustFailure")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        // https://www.asp.net/ajax/documentation/live/tutorials/TimerControlWithUpdatePanelsTutorial.aspx
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri);
        }

        protected void tmrLive_Tick(object sender, EventArgs e) 
        {
            Page_Load(sender,e);        
        }

    }
}